import * as THREE from "three";

var originFloor = null;

const floorHeight = 4;
export const createFloors = async (floorRange) => {
  if (!originFloor) {
    originFloor = await loadFloorModule();
  }
  const floors = arrangeFloor(floorRange);
  return floors;
};

const loadFloorModule = () => {
  return new Promise((resolve) => {
    const material = new THREE.MeshStandardMaterial({
      color: "#aaaaaa", // 基础颜色
      transparent: true,
      opacity: 1
      // metalness: 0, // 金属度（0-1）
      // roughness: 0.5, // 粗糙度（0-1）
      // envMap: envTexture,
      // envMapIntensity: 1 // 环境映射强度
    });

    const floorBody = new THREE.Mesh(new THREE.BoxGeometry(10, 3.5, 10), material);
    floorBody.name = "floorBody";
    floorBody.position.set(0, 1.75, 0);
    const floorTop = new THREE.Mesh(new THREE.BoxGeometry(11, 0.5, 11), material);
    floorTop.name = "floorTop";
    floorTop.position.set(0, 3.75, 0);
    const floor = new THREE.Group();
    floor.name = "floor";
    floor.add(floorBody, floorTop);
    resolve(floor);
  });
};

// 克隆模型并克隆材质
function cloneModelWithMaterial(model) {
  const clone = model.clone();

  // 递归遍历所有子对象
  clone.traverse((child) => {
    if (child.isMesh) {
      // 为每个网格创建材质副本
      if (child.material) {
        child.material = child.material.clone();
      }
    }
  });

  return clone;
}

const arrangeFloor = (floorRange) => {
  const floors = [];
  let curheight = 0;
  floorRange.forEach((item, index) => {
    let floor = cloneModelWithMaterial(originFloor);
    floor.position.set(0, curheight, 0);
    floor.userData = {
      name: `${index + 1} F`
    };
    floors.push(floor);
    curheight += floorHeight;
  });
  return floors;
};
